<template>
  <view class="page">
    <view class="navbar" :style="{background: 'rgba(255, 255, 255, '+opacityVal+')'}">
      <image style="width: 136rpx;height: 34rpx;" src="../../static/login/logoTitle.png" />
      <view class="search">
        <u-search placeholder="输入关键内容" borderColor="#F5F5F5" v-model="searchVal" @search="search" height="60rpx" bgColor="transparent" :showAction="false" searchIconColor="#333333" color="#333333"></u-search>
      </view>
    </view>
    <u-swiper :list="bannerList" @click="bannerClick" circular bgColor="#fff" height="600rpx" keyName="imageUrl"></u-swiper>
    <view class="special-zone">
      <view class="special-zone-item" @click="toPage('/pages/member/member')">
        <image style="width: 90rpx;height: 90rpx;" src="../../static/index/icon1.png" />
        <text>会员免费专区</text>
      </view>
      <view class="special-zone-item" @click="toPage('/pages/firstOrder/firstOrder')">
        <image style="width: 90rpx;height: 90rpx;" src="../../static/index/icon2.png" />
        <text>首单体验专区</text>
      </view>
      <view class="special-zone-item" @click="toPage('/pages/activateMembership/activateMembership')">
        <image style="width: 90rpx;height: 90rpx;" src="../../static/index/icon3.png" />
        <text>开通会员</text>
      </view>
    </view>
    <view class="u-flex u-row-between" style="width: 686rpx;margin: 0 auto 6rpx;" v-if="hotProductsList.length">
      <view class="u-flex u-col-top" style="gap: 10rpx;">
        <image style="width: 30.36rpx;height: 37.95rpx;" src="../../static/index/titleIcon1.png" />
        <image style="width: 260rpx;height: 48rpx;" src="../../static/index/title1.png" />
      </view>
      <!-- <view class="more">更多>></view> -->
    </view>
    <view class="bestseller" :style="'background-image: url('+bestseller+');'" v-if="hotProductsList.length">
      <view class="bestseller-item" v-for="item in hotProductsList" :key="item.id" @click="toPage('/pages/goodsDetail/goodsDetail?id='+item.id)">
        <image style="width: 200rpx;height: 200rpx;" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
        <view class="name u-line-2">{{ item.title }}</view>
        <view class="price"><text>¥</text> {{ (item.price / 100).toFixed(2) }}</view>
      </view>
    </view>
    <view class="u-flex u-row-between" style="width: 686rpx;margin: 0 auto 20rpx;">
      <view class="u-flex u-col-top" style="gap: 10rpx;">
        <image style="width: 40rpx;height: 40rpx;" src="../../static/index/titleIcon2.png" />
        <image style="width: 382rpx;height: 48rpx;" src="../../static/index/title2.png" />
      </view>
      <view class="more" @click="toPage('/pages/shop/shop', {}, 'jumpTab')">更多>></view>
    </view>
    <view class="type-list">
      <u-tabs
        :list="typeList"
        lineColor="#33692B"
        lineWidth="64rpx"
        inactiveStyle="color: #313131;"
        activeStyle="color: #33692B;"
        keyName="cateName"
        :current="tabsCurrent"
        @change="tabsChange"
        :scrollable="typeList.length > 3"
      >
      </u-tabs>
    </view>
    <view class="goods-list" v-if="goodsList.length">
      <view class="goods-item" v-for="item in goodsList" :key="item.id" @click="toPage('/pages/goodsDetail/goodsDetail?id='+item.id)">
        <image style="width: 140rpx;height: 140rpx;flex-shrink: 0;" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
        <view class="u-flex-1">
          <view class="name u-line-2">{{ item.title }}</view>
          <view class="u-flex u-row-between">
            <view class="price"><text>¥</text> {{ (item.priceCents/100).toFixed(2) }}</view>
            <view class="num">仅剩{{ item.totalInventory }}件</view>
          </view>
        </view>
      </view>
    </view>
    <a-empty v-else></a-empty>
    <customTabbar value="1" />
  </view>
</template>

<script>
import customTabbar from '../../components/customTabbar.vue'
import bestseller from '../../static/index/bestseller.png'
import { getBannersList, getCategoriesList, getProductsList, gethotProductsList, sendClickCount, saveInviteCode, getUserInfo } from '@/api/index'
import { utilWxLogin } from "@/common/util";

export default {
  components: {
    customTabbar,
  },
  data() {
    return {
      bestseller,
      opacityVal: 0,
      searchVal: '',
      bannerList: [],
      hotProductsList: [],
      typeList: [],
      tabsCurrent: 0,
      goodsNum: 1,
      goodsList: [],
      pages: 0,
    };
  },
  async onLoad(options) {
    console.log(options);
    if(options.invitationCode) {
      uni.setStorageSync('invitationCode', options.invitationCode)
    }
    if(uni.getStorageSync('noLogin') != '果然年代') {
      await utilWxLogin()
    }
    uni.removeStorageSync('noLogin')
    if(uni.getStorageSync('invitationCode') && uni.getStorageSync('userInfo') && uni.getStorageSync('userInfo').userId && !uni.getStorageSync('userInfo').invitationName) {
      const parameter = {
        userId: uni.getStorageSync('userInfo').userId,
        invitationCode: uni.getStorageSync('invitationCode'),
      }
      saveInviteCode(parameter).then(() => {
        getUserInfo({}).then(res => {
          uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
        })
      })
      uni.removeStorageSync('invitationCode')
    }
    uni.showLoading({ mask: true })
    await this.getBanner()
    await this.getCategories()
    await this.gethotProducts()
    uni.hideLoading()
  },
  methods: {
    bannerClick(index) {
      sendClickCount({ id: this.bannerList[index].id })
    },
    toPage(url, params, name = 'jumpTo') {
      if(uni.getStorageSync('token')) {
        this[name](url, params)
      } else {
        this.jumpTo('/pages/login/login')
      }
    },
    // 轮播图
    async getBanner() {
      await getBannersList({pageSize: 5, type: '3',status: '1', deptId: uni.getStorageSync('userInfo')?.deptId || 100}).then(res => {
        this.bannerList = res.rows
      })
    },
    // 商品分类
    async getCategories() {
      await getCategoriesList({pageSize: 50, categoryType: 0}).then(async res => {
        this.typeList = [{ cateName: '全部', id: '' }, ...res.rows]
        this.typeList.forEach(v => {
          v.cateName = '🍉 ' + v.cateName
        })
        this.goodsList = []
        await this.getProducts()
      })
    },
    tabsChange(e) {
      this.tabsCurrent = e.index
      this.goodsNum = 1
      this.goodsList = []
      this.getProducts()
    },
    // 热销榜单
    async gethotProducts() {
      uni.showLoading({ mask: true })
      await gethotProductsList({quantity: 3, categoryType: 0, deptId: uni.getStorageSync('userInfo').deptId || 100}).then(res => {
        uni.hideLoading()
        this.hotProductsList = res.data
      })
    },
    // 商品列表
    async getProducts() {
      uni.showLoading({ mask: true })
      await getProductsList({pageNum: this.goodsNum, pageSize: 20, status: 1, productType: '0', categoryId: this.typeList[this.tabsCurrent].id}).then(res => {
        uni.hideLoading()
        this.goodsList = [...this.goodsList, ...res.rows]
        this.pages = Math.ceil(res.total / 20)
      })
    },
    search(e) {
      uni.setStorageSync('searchVal', e)
      this.jumpTo('/pages/searchGoods/searchGoods')
    },
  },
  onReachBottom() {
    if(this.goodsNum < this.pages) {
      this.goodsNum++
      this.getProducts()
    }
  },
  onPageScroll(e) {
    const scrollThreshold = 200
    const scrollTop = e.scrollTop;
    if (scrollTop <= 0) return this.opacityVal = 0; // 滚动到顶部时透明度为0
		if (scrollTop >= scrollThreshold) return this.opacityVal = 1; // 超过阈值时透明度为1
		return this.opacityVal = (scrollTop / scrollThreshold).toFixed(1); // 线性计算透明度
  },
};
</script>

<style lang="scss" scoped>
.page {
	width: 750rpx;
	min-height: 100vh;
  background: #F5F5F5;
  position: relative;
  padding-bottom: 80rpx;
  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    width: 750rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 26rpx 32rpx;
    gap: 36rpx;
    .search {
      flex: 1;
      background: rgba(255,255,255,0.6);
      border-radius: 200rpx;
    }
  }
  .special-zone {
    width: 686rpx;
    height: 180rpx;
    border-radius: 12rpx 12rpx 12rpx 12rpx;
    background: rgba($color: #fff, $alpha: .4);
    backdrop-filter: blur(16rpx);
    margin: 0 auto;
    margin-top: -60rpx;
    margin-bottom: 32rpx;
    position: relative;
    display: flex;
    .special-zone-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      font-weight: 600;
      font-size: 28rpx;
      color: #073500;
    }
  }
  .more {
    font-size: 20rpx;
    color: #333333;
  }
  .bestseller {
    width: 686rpx;
    height: 360rpx;
    background-color: #fff;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    border-radius: 20rpx;
    margin: 0 auto;
    margin-bottom: 32rpx;
    display: flex;
    justify-content: space-evenly;
    .bestseller-item {
      width: 200rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .name {
        width: 100%;
        height: 88rpx;
        font-size: 24rpx;
        color: #000000;
        line-height: 44rpx;
      }
      .price {
        width: 100%;
        font-weight: 500;
        font-size: 28rpx;
        color: #E20300;
        text {
          font-size: 24rpx;
        }
      }
    }
  }
  .type-list {
    width: 686rpx;
    height: 88rpx;
    background: #FFFFFF;
    margin: 0 auto 12rpx;
  }
  .goods-list {
    width: 686rpx;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    margin: 0 auto;
    .goods-item {
      width: 100%;
      height: 180rpx;
      background: #fff;
      border-radius: 12rpx;
      display: flex;
      gap: 18rpx;
      padding: 20rpx 22rpx;
      .name {
        height: 88rpx;
        margin-bottom: 18rpx;
        font-size: 28rpx;
        color: #000000;
        line-height: 44rpx;
      }
      .price {
        font-weight: 500;
        font-size: 28rpx;
        color: #E20300;
        text {
          font-size: 24rpx;
        }
      }
      .num {
        font-size: 24rpx;
        color: #818181;
      }
    }
  }
}
</style>
